/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.money.web;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.modules.money.entity.Money;
import com.thinkgem.jeesite.modules.money.service.MoneyService;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 薪资管理Controller
 * @author zk
 * @version 2015-11-09
 */
@Controller
@RequestMapping(value = "${adminPath}/money/money")
public class MoneyController extends BaseController {

	@Autowired
	private MoneyService moneyService;
	
	@ModelAttribute
	public Money get(@RequestParam(required=false) String id) {
		Money entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = moneyService.get(id);
		}
		if (entity == null){
			entity = new Money();
		}
		return entity;
	}
	
	@RequiresPermissions("money:money:view")
	@RequestMapping(value = {"list", ""})
	public String list(Money money, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Money> page = moneyService.findPage(new Page<Money>(request, response), money); 
		model.addAttribute("page", page);
		return "modules/money/moneyList";
	}

	@RequiresPermissions("money:money:view")
	@RequestMapping(value = "form")
	public String form(Money money, Model model) {
		model.addAttribute("money", money);
		return "modules/money/moneyForm";
	}

	@RequiresPermissions("money:money:edit")
	@RequestMapping(value = "save")
	public String save(Money money, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, money)){
			return form(money, model);
		}
		moneyService.save(money);
		addMessage(redirectAttributes, "保存薪资记录成功");
		return "redirect:"+Global.getAdminPath()+"/money/money/?repage";
	}
	
	@RequiresPermissions("money:money:edit")
	@RequestMapping(value = "delete")
	public String delete(Money money, RedirectAttributes redirectAttributes) {
		moneyService.delete(money);
		addMessage(redirectAttributes, "删除薪资记录成功");
		return "redirect:"+Global.getAdminPath()+"/money/money/?repage";
	}

	
	/**
	 * 导入用户数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("money:money:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/money/money/list?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Money> list = ei.getDataList(Money.class);
			/*for (User user : list){
				try{
					if ("true".equals(checkLoginName("", user.getLoginName()))){
						user.setPassword(SystemService.entryptPassword("123456"));
						BeanValidators.validateWithException(validator, user);
						systemService.saveUser(user);
						successNum++;
					}else{
						failureMsg.append("<br/>登录名 "+user.getLoginName()+" 已存在; ");
						failureNum++;
					}
				}catch(ConstraintViolationException ex){
					failureMsg.append("<br/>登录名 "+user.getLoginName()+" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					failureMsg.append("<br/>登录名 "+user.getLoginName()+" 导入失败："+ex.getMessage());
				}
			}*/
			System.out.println("========导入数据==============");
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条薪资数据，导入信息如下：");
			}
			
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条用户薪资记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入薪资失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/money/money/list?repage";
    }
	
	/**
	 * 下载导入用户数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("money:money:view")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "薪资数据导入模板.xlsx";
    		List<Money> list = Lists.newArrayList();
    		Money money = new Money();
    		money.setId("1");
    		//money.setCreateDate(new Date());
    		money.setMoneys("2113.13");
    		money.setMoneyDate(new Date());
    		User user = new User();
    		user.setName("xx学习");
    		money.setUser(user);
    		list.add(money);
    		new ExportExcel("用户数据", Money.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/money/money/list?repage";
    }
}